package com.wn.icloud.plugin.generator;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;

/**
 * @author kyy
 * @date 2019/04/13
 */
public class CodeCopier extends BaseCodeGenerator {


    public CodeCopier(String mavenModuleName, String basePackage, String moduleName) {
        super(mavenModuleName, basePackage, moduleName);
    }

    public void copy(String type) throws IOException {

        String[] srcPs = {"src", "main", "java", basePackagePath, type};
        String srcDirPath = StringUtils.join(srcPs, File.separator);
        File srcDir = new File(srcDirPath);

        String[] destPs = {mavenModuleName, "src", "main", "java", basePackagePath, modulePath, type};
        String destDirPath = StringUtils.join(destPs, File.separator);
        File destDir = new File(destDirPath);
        //拷贝代码
        FileUtils.copyDirectory(srcDir, destDir);
        //批量修改包路径
        FileUtils.listFiles(destDir, new String[]{"java"}, true)
                .forEach(this::changeCodePackage);
    }


    private void changeCodePackage(File file) {
        try {
            String content = FileUtils.readFileToString(file, "UTF-8");
            content.replaceAll(basePackage, basePackage + "." + moduleName);
            FileUtils.writeStringToFile(file, content, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
